package com.atguigu.gmall.mq.receiver;

import com.atguigu.gmall.mq.config.DeadLetterConfig;
import com.atguigu.gmall.mq.config.DelayedMqConfig;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author: atguigu
 * @create: 2023-08-12 09:42
 */
@Slf4j
@Component
public class DelayMsgReceiver {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 监听延迟消息
     *
     * @param msg
     * @param channel
     * @param message
     */
    @SneakyThrows
    @RabbitListener(queues = DelayedMqConfig.queue_delay_1)
    public void receiveDelayMsg(String msg, Channel channel, Message message) {
        if (StringUtils.isNotBlank(msg)) {
            log.info("【mq监听】,监听到延迟消息：{}", msg);
            //1.判断业务场景是否需要进行幂等性处理  天然支持幂等：查询，删除，部分修改（boolean 将状态变更）
            //采用Redis set nx 命令 只有第一次key不存在 才能成功  后续多余消息忽略即可
            String key = "mq:" + msg;
            Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "", 5, TimeUnit.MINUTES);
            if (!flag) {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                return;
            }
            log.info("模拟业务处理");
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
